'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	let data = ''
	switch (event.action) {
		case 'sign':
			data = await sign(event.code)
			break;
		case 'setyb':
			data = await setyb(event.id)
			break;
		default:
			data = {
				msg: '未找到该方法',
				code: 404
			}
			break;
	}

	//返回数据给客户端
	return data
};
// 绑定易班
const setyb = async id => {
	console.log("id", id);
	await db.collection('uni-id-users').where({
		wx_openid: id.wx_openid
	}).update({
		yb_openid: id.yb_openid
	}).then(res => {
		console.log("success yiban update");
	})

	return {
		msg: '绑定成功',
		code: 200
	}
}
// 登录函数
const sign = async js_code => {
	let apiUrl = 'https://api.weixin.qq.com/sns/jscode2session'
	let params = {
		js_code,
		appid: 'wx527ff17bb2502e9d',
		secret: '18cc33a0437dea3ce1afe49a19d5665a',
		grant_type: 'authorization_code',
	}
	const res = await uniCloud.httpclient.request(apiUrl, {
		method: 'GET',
		data: params,
		contentType: 'json',
		dataType: 'json'
	})
	const wx_openid = res.data.openid
	const data = await db.collection('uni-id-users').where({
			wx_openid,
		}).get()
		.then(async res => {
			if (res.length != 0) {
				return {
					wx_openid,
					yb_openid: res.data[0].yb_openid
				}
			} else {
				await db.collection('uni-id-users').add({
					wx_openid
				})
				return {
					wx_openid,
					yb_openid: null
				}
			}
		})
	return data
}
